#!/usr/bin/env python

import zipfile
import os
import glob

from cStringIO import StringIO
from google.appengine.ext import db

import appengine_admin

class TheZipFile(db.Model):
	name = db.StringProperty()#(required=True)
	date = db.DateProperty()
	buildtype = db.StringProperty()
	smiles = db.StringProperty()
	sound = db.StringProperty()
	icons = db.StringProperty()
	locales = db.StringProperty()
	skins = db.StringProperty()
	data = db.BlobProperty()
	counter = db.IntegerProperty()
	url = db.StringProperty()
	whencreated = db.DateTimeProperty("Created", auto_now_add = True)
	whenupdated = db.DateTimeProperty("Updated", auto_now = True)
	stream = StringIO()
	stream.seek(0)
	TheZip = zipfile.ZipFile(stream, "w")
	def addDir(self, dirname):
		dirname = dirname.encode("ascii")
		for file in glob.glob(dirname + "/*"):
			if os.path.isfile(file):
				self.TheZip.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED)
			elif os.path.isdir(file):
				self.addDir(file) 
	def Make(self, distfiles, resources):		
		self.addDir(distfiles)
		for resource in resources:
			self.addDir(resource)
		self.stream.seek(0)		
		self.data = db.Blob(self.stream.read())
		self.stream.close()
		self.put()

class AdminZip(appengine_admin.ModelAdmin):
	model = TheZipFile
	listFields = ('name', 'whencreated', 'whenupdated')
	editFields = ('name', 'smiles', 'icons', 'locales', 'skins', 'data')
	readonlyFields = ('buildtype','data', 'whencreated', 'whenupdated')
appengine_admin.register(AdminZip)
